package com.ruoyi.combat.service.apprisk.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.apprisk.CombatAppRisk;
import com.ruoyi.combat.domain.apprisk.CombatApplication;
import com.ruoyi.combat.mapper.apprisk.CombatApplicationMapper;
import com.ruoyi.combat.service.apprisk.ICombatAppRiskService;
import com.ruoyi.combat.service.apprisk.YueQuanService;
import com.ruoyi.combat.util.ApKConstants;
import com.ruoyi.combat.util.YuequanTask;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.combat.mapper.apprisk.CombatAppTaskMapper;
import com.ruoyi.combat.domain.apprisk.CombatAppTask;
import com.ruoyi.combat.service.apprisk.ICombatAppTaskService;

import javax.annotation.PostConstruct;

/**
 * app检测任务Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-06
 */
@Service
@Slf4j
public class CombatAppTaskServiceImpl implements ICombatAppTaskService {
    @Autowired
    private CombatAppTaskMapper combatAppTaskMapper;

    @Autowired
    private YueQuanService yueQuanService;

    @Autowired
    private CombatApplicationMapper combatApplicationMapper;
    @Autowired
    private ICombatAppRiskService combatAppRiskService;
    @Autowired
    SysUserMapper sysUserMapper;


    /**
     * 项目启动时，初始化参数到缓存
     */
   /* @PostConstruct
    public void init()
    {
        ThreadUtil.execAsync(new Runnable() {
            @Override
            public void run() {
                loadingAppCheckTask();
            }
        });

    }*/

    /**
     * 项目启动时，加载所有需要检测的app
     */
    public void loadingAppCheckTask() {
//        while (true){
        try {
            CombatAppTask combatAppTask = new CombatAppTask();
            combatAppTask.setStatus("0");
            List<CombatAppTask> list = combatAppTaskMapper.selectCombatAppTaskList(combatAppTask);
            if (list != null) {
                log.info("加载检测任务:" + list.size());
                for (CombatAppTask combatAppTask1 : list) {
                    Long appId = combatAppTask1.getAppId();
                    Long userId = combatAppTask1.getUserId();
                    Long id = combatAppTask1.getId();
                    try {
                        if (appId != null) {
                            CombatApplication combatApplication = combatApplicationMapper.selectCombatApplicationByAppid(appId);
                            if (combatApplication != null) {
                                if (userId != null) {
                                    yueQuanService.service(combatApplication, userId);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("加载检测任务异常:" + e.getMessage());
                    }
                    combatAppTask1 = new CombatAppTask();
                    combatAppTask1.setId(id);
                    combatAppTask1.setStatus("1");
                    combatAppTask1.setUpdateTime(new Date());
                    combatAppTaskMapper.updateCombatAppTask(combatAppTask1);
                }
            }
//                Thread.sleep(10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        }
    }

    public static void main1(String[] args) {
        String data3Str = "[\n" +
                "  {\n" +
                "    \"EscalationAPP\": \"com.example.app1\",\n" +
                "    \"EscalationMD5\": \"cbe6a6e17338c1c6bdf3b72f2a68c859\",\n" +
                "    \"Permission\": \"android.permission.READ_PHONE_STATE\",\n" +
                "    \"ProviderAPP\": \"com.example.app3\",\n" +
                "    \"ProviderMD5\": \"7a1abd5944c3dcd2a0f8d8b1528f68a9\",\n" +
                "    \"Sensitive Method\": \"android.telephony.TelephonyManage:getImei\"\n" +
                "  }\n" +
                "]";
        List<Map> list = JSONUtil.toList(data3Str, Map.class);


    }

    @Override
    public void sendCheckResult(List<Map> data) {
        if (data != null) {
            Long userId = null;
            Long appid = null;
            for (Map map : data) {
                String EscalationAPP = String.valueOf(map.get("EscalationAPP"));
                String EscalationMD5 = String.valueOf(map.get("EscalationMD5"));
                String Permission = String.valueOf(map.get("Permission"));
                String ProviderAPP = String.valueOf(map.get("ProviderAPP"));
                String ProviderMD5 = String.valueOf(map.get("ProviderMD5"));
                String Method = String.valueOf(map.get("Sensitiv Method"));
                String MatchFlag = String.valueOf(map.get("MatchFlag"));

                String permissionName = "";
                if (Method.contains("getCellLocation") || Method.contains("getCid") || Method.contains("getLac")) {
                    permissionName = "基站";
                } else {
                    permissionName = ApKConstants.getPermissionName(Permission);
                }

                CombatApplication combatApplication = new CombatApplication();
                combatApplication.setAppPkgname(EscalationAPP);
                combatApplication.setAppMd5(EscalationMD5);
                List<CombatApplication> combatApplications = combatApplicationMapper.selectCombatApplicationList(combatApplication);
                if (combatApplications != null && combatApplications.size() > 0) {
                    CombatApplication app = combatApplications.get(0);
                    appid = app.getAppid();
                    String upperCase = app.getAppSha256().toUpperCase();
                    String appPkgname = app.getAppPkgname();
                    CombatAppRisk appRisk = new CombatAppRisk();
                    appRisk.setAppId(appid);
                    appRisk.setRiskContent(permissionName);
                    List<CombatAppRisk> combatAppRisks = combatAppRiskService.selectCombatAppRiskList(appRisk);
                    if (combatAppRisks == null || combatAppRisks.size() == 0) {
                        CombatAppRisk combatAppRisk = new CombatAppRisk();
                        combatAppRisk.setAppId(combatApplications.get(0).getAppid());
                        combatAppRisk.setRiskType("越权访问");
                        combatAppRisk.setRiskContent(permissionName);
                        combatAppRisk.setTestime(new Date());
                        combatAppRisk.setTopic("3");
                        combatAppRiskService.insertCombatAppRisk(combatAppRisk);
                    }else {
                        CombatAppRisk combatAppRisk = combatAppRisks.get(0);
                        String topic = combatAppRisk.getTopic();
                        if (topic == null || topic.equals("")) {
                            combatAppRisk.setTopic("3");
                            combatAppRiskService.updateCombatAppRisk(combatAppRisk);
                        }else if(!topic.contains("3")){
                            topic = topic + ",3";
                            combatAppRisk.setTopic(topic);
                            combatAppRiskService.updateCombatAppRisk(combatAppRisk);
                        }
                    }
                }

                combatApplication = new CombatApplication();
                combatApplication.setAppPkgname(ProviderAPP);
                combatApplication.setAppMd5(ProviderMD5);
                combatApplications = combatApplicationMapper.selectCombatApplicationList(combatApplication);
                if (combatApplications != null && combatApplications.size() > 0) {
                    CombatApplication app = combatApplications.get(0);
                    appid = app.getAppid();
                    String upperCase = app.getAppSha256().toUpperCase();
                    String appPkgname = app.getAppPkgname();
                    CombatAppRisk appRisk = new CombatAppRisk();
                    appRisk.setAppId(appid);
                    appRisk.setRiskContent(permissionName);
                    List<CombatAppRisk> combatAppRisks = combatAppRiskService.selectCombatAppRiskList(appRisk);
                    if (combatAppRisks == null || combatAppRisks.size() == 0) {
                        CombatAppRisk combatAppRisk = new CombatAppRisk();
                        combatAppRisk.setAppId(combatApplications.get(0).getAppid());
                        combatAppRisk.setRiskType("越权访问");
                        combatAppRisk.setRiskContent(permissionName);
                        combatAppRisk.setTestime(new Date());
                        combatAppRisk.setTopic("3");
                        combatAppRiskService.insertCombatAppRisk(combatAppRisk);
                    }else {
                        CombatAppRisk combatAppRisk = combatAppRisks.get(0);
                        String topic = combatAppRisk.getTopic();
                        if (topic == null || topic.equals("")) {
                            combatAppRisk.setTopic("3");
                            combatAppRiskService.updateCombatAppRisk(combatAppRisk);
                        }else if(!topic.contains("3")){
                            topic = topic + ",3";
                            combatAppRisk.setTopic(topic);
                            combatAppRiskService.updateCombatAppRisk(combatAppRisk);
                        }
                    }
                }
            }
            CombatAppTask combatAppTask = new CombatAppTask();
            combatAppTask.setUserId(userId);
            combatAppTask.setAppId(appid);
            List<CombatAppTask> combatAppTasks = combatAppTaskMapper.selectCombatAppTaskList(combatAppTask);
            CombatAppTask combatAppTask1 = combatAppTasks.get(0);
            Long id = combatAppTask1.getId();
            combatAppTask1 = new CombatAppTask();
            combatAppTask1.setId(id);
            combatAppTask1.setStatus3("2");
            combatAppTaskMapper.updateCombatAppTask(combatAppTask1);
        }
    }

    @Override
    public void sendCheck1Result(Map data) {
        if (data != null) {
            String appName = String.valueOf(data.get("app_name"));
            String appType = String.valueOf(data.get("app_type"));
            String md5 = String.valueOf(data.get("MD5"));
            List<String> dangerous_permission_categories = (List<String>) data.get("dangerous_permission_categories");

            Long userId = null;
            Long appid = null;
            CombatApplication combatApplication = new CombatApplication();
//            combatApplication.setAppPkgname(EscalationAPP);
            combatApplication.setAppMd5(md5);
            List<CombatApplication> combatApplications = combatApplicationMapper.selectCombatApplicationList(combatApplication);
            if (combatApplications != null && combatApplications.size() > 0) {
                CombatApplication app = combatApplications.get(0);
                appid = app.getAppid();
                String upperCase = app.getAppSha256().toUpperCase();
                String appPkgname = app.getAppPkgname();
                for (String content : dangerous_permission_categories) {
                    CombatAppRisk appRisk = new CombatAppRisk();
                    appRisk.setAppId(appid);
                    appRisk.setRiskContent(content);
                    List<CombatAppRisk> combatAppRisks = combatAppRiskService.selectCombatAppRiskList(appRisk);
                    if (combatAppRisks == null || combatAppRisks.size() == 0) {
                        CombatAppRisk combatAppRisk = new CombatAppRisk();
                        combatAppRisk.setAppId(combatApplications.get(0).getAppid());
                        combatAppRisk.setRiskType("越权访问");
                        combatAppRisk.setRiskContent(content);
                        combatAppRisk.setTestime(new Date());
                        combatAppRisk.setTopic("1");
                        combatAppRiskService.insertCombatAppRisk(combatAppRisk);
                    }else {
                        CombatAppRisk combatAppRisk = combatAppRisks.get(0);
                        String topic = combatAppRisk.getTopic();
                        if (topic == null || topic.equals("")) {
                            combatAppRisk.setTopic("1");
                            combatAppRiskService.updateCombatAppRisk(combatAppRisk);
                        }else if(!topic.contains("1")){
                            topic = topic + ",1";
                            combatAppRisk.setTopic(topic);
                            combatAppRiskService.updateCombatAppRisk(combatAppRisk);
                        }
                    }
                }
            }

            CombatAppTask combatAppTask = new CombatAppTask();
            combatAppTask.setUserId(userId);
            combatAppTask.setAppId(appid);
            List<CombatAppTask> combatAppTasks = combatAppTaskMapper.selectCombatAppTaskList(combatAppTask);
            CombatAppTask combatAppTask1 = combatAppTasks.get(0);
            Long id = combatAppTask1.getId();
            combatAppTask1 = new CombatAppTask();
            combatAppTask1.setId(id);
            combatAppTask1.setStatus1("2");
            combatAppTaskMapper.updateCombatAppTask(combatAppTask1);

        }

    }

    /**
     * 查询app检测任务
     *
     * @param id app检测任务主键
     * @return app检测任务
     */
    @Override
    public CombatAppTask selectCombatAppTaskById(Long id) {
        return combatAppTaskMapper.selectCombatAppTaskById(id);
    }

    /**
     * 查询app检测任务列表
     *
     * @param combatAppTask app检测任务
     * @return app检测任务
     */
    @Override
    public List<CombatAppTask> selectCombatAppTaskList(CombatAppTask combatAppTask) {
        List<CombatAppTask> combatAppTasks = combatAppTaskMapper.selectCombatAppTaskList(combatAppTask);
        for (CombatAppTask task : combatAppTasks) {
            CombatApplication combatApplication1 = combatApplicationMapper.selectCombatApplicationByAppid(task.getAppId());
            task.setAppName(combatApplication1.getAppName());
            SysUser user = sysUserMapper.selectUserById(task.getUserId());
            task.setUserName(user.getNickName());
        }
        return combatAppTasks;
    }

    /**
     * 新增app检测任务
     *
     * @param combatAppTask app检测任务
     * @return 结果
     */
    @Override
    public int insertCombatAppTask(CombatAppTask combatAppTask) {
        combatAppTask.setCreateTime(DateUtils.getNowDate());
        return combatAppTaskMapper.insertCombatAppTask(combatAppTask);
    }

    /**
     * 修改app检测任务
     *
     * @param combatAppTask app检测任务
     * @return 结果
     */
    @Override
    public int updateCombatAppTask(CombatAppTask combatAppTask) {
        combatAppTask.setUpdateTime(DateUtils.getNowDate());
        return combatAppTaskMapper.updateCombatAppTask(combatAppTask);
    }

    /**
     * 批量删除app检测任务
     *
     * @param ids 需要删除的app检测任务主键
     * @return 结果
     */
    @Override
    public int deleteCombatAppTaskByIds(Long[] ids) {
        return combatAppTaskMapper.deleteCombatAppTaskByIds(ids);
    }

    /**
     * 删除app检测任务信息
     *
     * @param id app检测任务主键
     * @return 结果
     */
    @Override
    public int deleteCombatAppTaskById(Long id) {
        return combatAppTaskMapper.deleteCombatAppTaskById(id);
    }


}
